'use strict';

var baseUrl = '';

var doMock = function($mock, callback) {
	if ($mock.error) {
		callback($mock.error);
	} else {
		callback(null, $mock.data);
	}
};

// 数据API
var Truedata = {
	query: function(option, callback) {
		// 模拟测试模式
		if (option.$mock) {
			doMock(option.$mock, callback);
			return;
		}

		var ajax = new XMLHttpRequest();
		ajax.onreadystatechange = function() {
			if (ajax.readyState != 4) {
				return;
			}
			if (ajax.status == 200) {
				try {
					var result = JSON.parse(ajax.responseText);
					callback(null, result);
				} catch (err) {
					callback(err);
				}
			} else {
				callback(new Error(ajax.statusText));
			}
		};
		var requestUrl = baseUrl + '/druid-1.1.6-SNAPSHOT/sqlparser';
		ajax.open('POST', requestUrl);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send('sql=' + encodeURIComponent(option.params.sql));
	}
};
module.exports = Truedata;
